#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/6/28  9:14
# @Author: 余浪人
# @email: yulangren520@gmail.com
from django.core.paginator import Paginator


def navigationList(objList: list, pid: str = '0'):
    '''
    序列化导航
    :param objList: 分类列表
    :param pid: 上级分类ID
    :return: 序列化集
    '''
    result = []
    for obj in objList:
        if str(obj.column_parent) == str(pid):
            if obj.column_link.strip(): result.append(dict(obj))
            findNav = navigationList(objList, obj.uuid)
            if len(findNav):
                result.extend(findNav)
            else:
                result.append(dict(obj))
    return result


def novelSerialize(obj,chapter:int=0):
    '''
    序列化小说
    :param obj: 书对象
    :return: 书与章节信息
    '''
    old = dict(obj)
    chapterList = obj.chapter_novel.all()[::-1] if chapter==0 else obj.chapter_novel.all()[::-1][:chapter]
    old['categories'] = obj.categories.column_name
    old['categoriesId'] = obj.categories.uuid
    old['chapter'] = [
        {'title': d.title, 'is_pay': False, 'novel': d.novel.novel_name, 'update_time': d.update_time, 'content_id': d.content_id, 'content_path': d.content_path,'uuid':d.uuid}
        for d in chapterList
    ]
    old['len'] = len(old['chapter'])
    return old

def PaginatorPage(request, data_all):
    '''
    接口分页
    :param request: 请求
    :param data_all: 全部数据
    :return:
    '''
    page = request.GET.get('page', '1')
    page_size = request.GET.get('page_size', '10')
    try:
        page = int(page)
    except:
        page = 1
    try:
        page_size = int(page_size)
    except:
        page_size = 10
    all_page = Paginator(data_all, page_size)
    try:
        data = all_page.page(page)
    except:
        data = all_page.page(1)
    return data, all_page